package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	pd "ycc_grpc_study/hello-server/proto"
)

type ClientTokenAuth struct {
}

// token 验证方法
func (c ClientTokenAuth) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
	return map[string]string{
		"appid":  "123456",
		"appkey": "123456",
	}, nil
}

// token 验证方法
// RequireTransportSecurity indicates whether the credentials requires
// transport security.
func (c ClientTokenAuth) RequireTransportSecurity() bool {
	return false
}

func main() {
	// TSL 认证
	// 客户端检验证书方法 域名在正式服务器上面需要手动获取,进行校验
	//credent, _ := credentials.NewClientTLSFromFile("D:\\project_go\\src\\ycc_grpc_study\\key\\test.pem", "*.yccstudy.com")
	// 连接到 server端,此处禁用安全传输,没有加密和验证
	// 如果没有校验 insecure.NewCredentials()
	// 当前使用 TSL 认证
	//conn, err := grpc.Dial("127.0.0.1:9090", grpc.WithTransportCredentials(credent))

	// token 验证方式
	var opts []grpc.DialOption
	opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
	opts = append(opts, grpc.WithPerRPCCredentials(new(ClientTokenAuth)))
	conn, err := grpc.Dial("127.0.0.1:9090", opts...)
	if err != nil {
		fmt.Println("grpc dial connect error: ", err)
		return
	}
	defer conn.Close()

	// 建立连接
	client := pd.NewSayHelloClient(conn)
	// 执行 rpc 调用(这个方法在服务器端来实现并返回结果)
	resp, _ := client.SayHello(context.Background(), &pd.HelloRequest{RequestName: "ycc"})

	fmt.Println(resp.GetResponseMsg())
}
